const chokidar = require('chokidar');
const { spawn } = require('child_process');
const path = require('path');

// 配置监听路径
const srcPath = path.join(__dirname, '../src');
const autoImportScript = path.join(__dirname, './autoImport.js');
const tsNodeScript = path.join(__dirname, './tsconfig-paths-bootstrap.js');
const indexTsPath = path.join(__dirname, '../src/index.ts');

let isAutoImportRunning = false;
let tsNodeProcess = null;

// 启动 ts-node-dev 进程
const startTsNodeDev = () => {
  console.log('🚀 启动 ts-node-dev...');
  tsNodeProcess = spawn('npx', [
    'ts-node-dev',
    '-r', tsNodeScript,
    '--respawn',
    indexTsPath
  ], {
    stdio: 'inherit',
    shell: true
  });

  tsNodeProcess.on('error', (err) => {
    console.error('ts-node-dev 启动失败:', err);
  });

  tsNodeProcess.on('exit', (code) => {
    console.log(`ts-node-dev 进程退出，退出码: ${code}`);
  });
};

// 运行自动导入脚本
const runAutoImport = () => {
  if (isAutoImportRunning) {
    console.log('⏳ 自动导入脚本正在运行，跳过...');
    return;
  }

  isAutoImportRunning = true;

  const autoImportProcess = spawn('node', [autoImportScript], {
    stdio: 'inherit',
    shell: true
  });

  autoImportProcess.on('close', (code) => {
    console.log(`✅ 自动导入脚本完成，退出码: ${code}`);
    isAutoImportRunning = false;
  });

  autoImportProcess.on('error', (err) => {
    console.error('❌ 自动导入脚本运行失败:', err);
    isAutoImportRunning = false;
  });
};

// 监听文件变化
const watcher = chokidar.watch(srcPath, {
  ignored: [
    // 忽略 node_modules
    '**/node_modules/**',
    // 忽略自动导入脚本产生的改动
    indexTsPath,
    // 忽略临时文件
    '**/*.tmp',
    '**/*.temp',
    '**/.DS_Store'
  ],
  persistent: true,
  ignoreInitial: true
});

// 监听文件变化事件
watcher
  .on('add', (filePath) => {
    console.log(`📄 新增文件: ${path.relative(srcPath, filePath)}`);
    runAutoImport();
  })
  .on('change', (filePath) => {
    console.log(`📝 文件变化: ${path.relative(srcPath, filePath)}`);
    runAutoImport();
  })
  .on('unlink', (filePath) => {
    console.log(`🗑️ 删除文件: ${path.relative(srcPath, filePath)}`);
    runAutoImport();
  })
  .on('addDir', (dirPath) => {
    console.log(`📁 新增目录: ${path.relative(srcPath, dirPath)}`);
    runAutoImport();
  })
  .on('unlinkDir', (dirPath) => {
    console.log(`🗑️ 删除目录: ${path.relative(srcPath, dirPath)}`);
    runAutoImport();
  })
  .on('error', (error) => {
    console.error('❌ 监听错误:', error);
  })
  .on('ready', () => {
    runAutoImport()
    console.log('✅ 文件监听器准备就绪');
    // 启动 ts-node-dev
    startTsNodeDev();
  });

// 优雅退出处理
process.on('SIGINT', () => {
  console.log('\n🛑 正在关闭监听器...');
  watcher.close();
  if (tsNodeProcess) {
    tsNodeProcess.kill('SIGINT');
  }
  process.exit(0);
});

process.on('SIGTERM', () => {
  console.log('\n🛑 正在关闭监听器...');
  watcher.close();
  if (tsNodeProcess) {
    tsNodeProcess.kill('SIGTERM');
  }
  process.exit(0);
});